﻿using d1Common.WebController;
using d1Project.Modules.Common.do4A.Models;
using d1Project.Tools;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace d1Project.Modules.Common.do4A.Controllers.a1
{
    [Route("do4A/a1/User3Pwd")]
    public class User3PwdController : Authorize1Controller
    {
        protected override DbContext dbContext
        {
            get
            {
                return this.db;
            }
        }
        private do4ADbContext db = new do4ADbContext();

        /// <summary>
        /// 重置密码 用户3
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [PermissionCheck(Id = "do4A$User3", Operation = 16)]
        public async Task<IHttpActionResult> Put(User3PwdVm model)
        {
            if (!ModelState.IsValid) this.Error("请求参数不正确");

            var _user3 = await db.User3s.FindAsync(model.Id);
            if (_user3 == null) this.Error("用户不存在");

            string pwd = "";
            if (string.IsNullOrEmpty(model.Password))
            {
                pwd = TextHelper.GetMd5("123456");
            }
            else
            {
                pwd = model.Password;
            }

            var user3Pwds = await db.User3Pwds.FindAsync(model.Id);
            if (user3Pwds == null)
            {
                User3Pwd entity = new User3Pwd();
                entity.Id = model.Id;
                entity.Password = pwd;
                db.User3Pwds.Add(entity);
            }
            else
            {
                user3Pwds.Password = pwd;
            }
            await db.SaveChangesAsync();
            return Ok();
        }
    }

    public class User3PwdVm
    {
        /// <summary>
        /// 用户Id
        /// </summary>
        [Required]
        public string Id { get; set; }

        /// <summary>
        /// 新密码
        /// </summary>
        public string Password { get; set; }
    }
}
